
#include "EventLoopThread.h"
#include "EventLoop.h"

void EventLoopThread::EntryThread() {
    EventLoop loop;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }
    loop_->Loop();
    loop_ = nullptr;
}

EventLoopThread::EventLoopThread() : loop_(nullptr), thread_(std::thread(&EventLoopThread::EntryThread, this)) {}

EventLoop* EventLoopThread::SelfEventLoop() {
    EventLoop* loop;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        cond_.wait(lock, [this]() { return loop_ != nullptr; });
        return loop_;
    }
}

EventLoopThread::~EventLoopThread() {
    if (loop_) {
        loop_->Quit();  // 停止事件循环
    }
    if (thread_.joinable()) {
        thread_.join();  // 等待线程结束
    }
}
